import QtQuick 2.0
import "./Custom"

ScreenBase{
    id: bg3
    anchors.fill: parent
    source: "qrc:/images/bg3.png"
    Keys.enabled: true
//    focus: true

    property var swordsArray: new Array
    property var monstersArray: new Array
    property real gLevel: 0

    Keys.onPressed:
    {
        if(gameover) return
        if(event.key === Qt.Key_Space)
        {
            console.log("Qt.Key_Space")
        }
        else if(event.key === Qt.Key_A)
        {
            player.moveToLeft(true)
        }
        else if(event.key === Qt.Key_D)
        {
            player.moveToRight(true)
        }
        else if(event.key === Qt.Key_W)
        {
            player.moveToUp(true)
        }
        else if(event.key === Qt.Key_S)
        {
            player.moveToDown(true)
        }
    }
    Keys.onReleased:
    {
        if(gameover) return
        if(event.key === Qt.Key_Space)
        {
        }
        else if(event.key === Qt.Key_A)
        {
            player.moveToLeft(false)
        }
        else if(event.key === Qt.Key_D)
        {
            player.moveToRight(false)
        }
        else if(event.key === Qt.Key_W)
        {
            player.moveToUp(false)
        }
        else if(event.key === Qt.Key_S)
        {
            player.moveToDown(false)
        }
    }

    function update()
    {
        player.update()

        var len = swordsArray.length
        for(var i in swordsArray)
        {
            var obj = swordsArray[i]

            // 武器 飞行
            obj.update()

            // 检测武器飞出屏幕外面
            var die = false

            if(obj.x <= -200) die = true
            else if(obj.x >= _WIDTH + 200) die = true
            else if(obj.y <= -200) die = true
            else if(obj.y >= _HEIGHT + 200) die = true

            if(die)
            {
                swordsArray.splice(i, 1)
                obj.destroy()
                console.log("die swordsArray.length ", i, swordsArray.length, "/", len)
            }
        }

        // move
        for(var j in monstersArray)
        {
            var monster = monstersArray[j]
            monster.update()
        }

        // 攻击怪物
        for(var m in swordsArray)
        {
            for(var n in monstersArray)
            {
                var r = checkCollision(swordsArray[m], monstersArray[n])
                if(r)
                {
                    monstersArray[n].hitSelf(swordsArray[m].damage)

//                    console.log("die swordsArray.length befor ", swordsArray.length)
                    var obj = swordsArray[m]
                    obj.destroy()
                    swordsArray.splice(m, 1)
//                    console.log("die swordsArray.length ", swordsArray.length)
                    break
                }
            }
        }
    }

    function setRole(v)
    {
        player.setRole(v)
    }

    function startNextLevel()
    {
        gLevel += 1

        reset()

        for(var i = 0; i < 3; ++i)
        {
            createMonster(i)
        }
    }

    function reset()
    {
        var len = swordsArray.length
        for(var i = len -1; i >= 0; --i)
        {
            var obj = swordsArray[i]
            obj.destroy()
            swordsArray.splice(i, 1)
        }
        swordsArray.length = 0
        swordsArray = new Array

        for(var i in monstersArray)
        {
            monstersArray[i].destroy()
            monstersArray.splice(i, 1)
        }
        monstersArray = new Array

        player.healthy = player._MAX_HEALTHY = gLevel * 10

        player.x = 100
        player.y = parent.height-100
        player.toRight = false
        player.toDown = false
        player.toLeft = false
        player.toUp = false

        gameover = false
    }

    function createMonster(iid)
    {
        var obj = Qt.createComponent("Monster.qml").createObject(items)
        obj.setRole(0)
        obj.x = getRandom(_WIDTH/2) + _WIDTH/2 - 100
        obj.y = getRandom(_HEIGHT/2)
        obj.iid = iid

        monstersArray.push(obj)
    }

    function createSword(angle)
    {
        console.log("createSword ", swordsArray.length)
        var sword = Qt.createComponent("Custom/FlyingSword.qml").createObject(items)

        var pos = player.getSendWeaponPos()
        sword.x = pos.x
        sword.y = pos.y - sword.height/2
        sword.setAngle(angle)

        swordsArray.push(sword)
    }

    function getMouseToPlayerAngle(mx, my)
    {
        var playerCenterPos = Qt.point(player.x+player.width/2, player.y+player.height/2)
        var radian = Math.atan2(playerCenterPos.y - my, playerCenterPos.x - mx)
        var angle = radian / Math.PI * 180
        return angle
    }

    function getPlayerCenterPox()
    {
        var pos = Qt.point(player.x + player.width/2, player.y + player.height/2)
        return pos
    }

    function getPlayerObj() { return player }

    // AABB
    function checkCollision(objA, objB)
    {
        var objACenter = Qt.point(objA.x+objA.width/2, objA.y+objA.height/2)
        var objBCenter = Qt.point(objB.x+objB.width/2, objB.y+objB.height/2)

        var xSpace = 0
        var ySpace = 0

        if(Math.abs(objACenter.x - objBCenter.x) <= objA.width/2+objB.width/2 - xSpace
                && Math.abs(objACenter.y - objBCenter.y) <= objA.height/2+objB.height/2 - ySpace)
        {
            return true
        }

        return false
    }

    function deleteMonster(iid)
    {
        for(var i in monstersArray)
        {
            if(monstersArray[i].iid === iid)
            {
                monstersArray[i].destroy()
                monstersArray.splice(i, 1)
                console.log("monstersArray len ", monstersArray.length)
                gameIsOver()
            }
        }
    }

    function gameIsOver()
    {
        if(monstersArray.length <= 0)
        {
            gameover = true
            menu.show()
        }
    }

    property real holdX: 0
    property real holdY: 0

    MouseArea{
        anchors.fill: parent
        hoverEnabled: true
        enabled: !gameover
        onPositionChanged: {
            var angle = getMouseToPlayerAngle(mouseX, mouseY)
            player.setAngle(angle)

            holdX = mouseX
            holdY = mouseY
        }
        acceptedButtons: Qt.LeftButton | Qt.RightButton
        onPressed: {
            if(gameover) return
            if(mouse.button === Qt.LeftButton)
            {
                // 发飞剑
                var angle = getMouseToPlayerAngle(mouseX, mouseY)
                createSword(angle)
            }
        }
        onPressAndHold:
        {
            if(gameover) return
            if(mouse.button === Qt.LeftButton || mouse.button === Qt.NoButton)
            {
                // 发飞剑
                timerCreateWeapon.restart()
            }
        }
        onReleased: {
            // 松手
            timerCreateWeapon.stop()
        }
    }

    Timer{
        id: timerCreateWeapon
        repeat: true
        interval: 300
        triggeredOnStart: true
        onTriggered: {
            if(gameover) return
            var angle = getMouseToPlayerAngle(holdX, holdY)
            createSword(angle)
        }
    }

    Item{
        id: items
        anchors.fill: parent
    }

    Player{
        id: player
        x: 100
        y: parent.height-100
    }

    TextBase{
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.bottom: rectBg.top
        anchors.bottomMargin: 10
        text: "体力: " + player.healthy + "/" + player._MAX_HEALTHY
    }

    // 生命条
    Rectangle{
        id: rectBg
        color: "black"
        width: 300
        height: 10
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 10

        Rectangle{
            color: "red"
            width: rectBg.width * player.healthy / player._MAX_HEALTHY
            height: rectBg.height
        }
    }

    GameMenu{
        id: menu
    }
}
